package com.eascs.banknet.boc.service.trans;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.jdom.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.banknet.boc.dao.BOCB01Dao;
import com.eascs.banknet.boc.dao.DataListDao;
import com.eascs.banknet.boc.service.BOCAbstractService;
import com.eascs.banknet.boc.vo.bocB01.BOCB01Bean;
import com.eascs.banknet.boc.vo.bocB01.BOCB01Element;
import com.eascs.banknet.boc.vo.bocB01.BOCB01Root;
import com.eascs.banknet.common.entity.DataListEntity;
import com.eascs.banknet.common.utils.XmlHelp;
import com.eascs.banknet.constant.EAContant;
import com.eascs.banknet.constant.FileTypeConstants;
import com.eascs.banknet.log.entity.LogEntity;
import com.eascs.common.util.StringUtil;

/**
 * 中行贷前调查
 * 征信流程：EA发送B01交易，中行解析征信报告并发送004意见反馈给EA，中行收到成功的返回后更新征信状态，接着EA发B02交易获取交易状态并更新到数据库，EA定时去中行FTP拉取已同意贷前调查的征信报告
 * @author Administrator
 *
 */
@Service("bocB01Service")
public class BOCB01Service extends BOCAbstractService {
	private static final Logger logger = LoggerFactory.getLogger(BOCB01Service.class);
	
	@Autowired
	private BOCB01Dao bocB01Dao;
	@Autowired
	private DataListDao datalistDao;
	
	private String startId;
	
	@Override
	public LogEntity initLogData() {
		LogEntity logEntity = new LogEntity();
		logEntity.setBankType(LogEntity.BANK_TYPE_BOC);
		logEntity.setTransType("B01");
		logEntity.setTypeName("贷前调查");
		logEntity.setStartTime(new Date());
		return logEntity;
	}
	
	@Override
	public Map<String, String> dowork() {
		//不管成功or失败，都要记录当前执行startId，用于下一次轮询开始的标记，若没有扫描到数据则重置startId重新开始
		Map<String, String> result = new HashMap<>();
		String loanapplyNo = "";
		String billCode = "";
		String id = "";	
		String appno = "";	//申请编号
		LogEntity logEntity = initLogData();
		try {
			logger.info("征信调查开始......");
			BOCB01Root root = new BOCB01Root();
			List<BOCB01Bean> dataList = bocB01Dao.queryData(startId);
			if(dataList.isEmpty()){
				startId = null;
				logger.info("BOCB01征信调查,没有符合条件的数据");
				return null;
			}
			BOCB01Bean bOCB01Bean = dataList.get(0);
			id = bOCB01Bean.getLoanUserId();
			loanapplyNo = bOCB01Bean.getLoanapplyNo();
			billCode = bOCB01Bean.getBillCode();
			startId = billCode;	
			//组装请求的xml消息
			List<BOCB01Element> elementList = new ArrayList<>();
			for(BOCB01Bean bean : dataList){
				BOCB01Element element = new BOCB01Element();
				BeanUtils.copyProperties(element, bean);
				element.setCCTPERTRN_CBICERTY(EAContant.IDTypeMap.get(bean.getCCTPERTRN_CBICERTY()));
				//中行测试环境只能用这个
				if("26.127.253.48".equals(bocUtil.getBocSocketInfo().getHref())){
					element.setCCTPERTRN_PERFSTNM("红丽");
					element.setCCTPERTRN_PERLSTNM("杨");
					element.setCCTPERTRN_CBICERNO("412926197205234920");
				}
				elementList.add(element);
			}
			root.getBody().setList(elementList);
			//保存xml文件到ftp服务器
			String xml = XmlHelp.convertToXml(root);
			
			logger.info("组装请求数据完成，开始调用中行B01接口, loanapplyNo:{}, xml:{}", loanapplyNo, xml);
			String returnXml = bocNetService.executeSocket(bocUtil.getBocSocketInfo(),  "B01", null, xml);
			logger.info("中行B01接口返回xml完成, returnXml：{}", returnXml);
			if(StringUtil.isEmpty(returnXml)){
				logger.error("中行B01接口返回数据为空！");
				throw new Exception("中行B01接口返回数据为空");
			}
			
			Element rsRoot = XmlHelp.getRootByString(returnXml);
			Element head = rsRoot.getChild("HEADER");
			Element body = rsRoot.getChild("BODY");
			String trncod_rs = head.getChildText("RETCODE")==null?"":head.getChildText("RETCODE");
			if (!EAContant.BOC001RS.equals(trncod_rs.toLowerCase())) {
				throw new Exception(head.getChildText("NOTE"));
			}
			Element trn = body.getChild("OUTPUT");
			appno = trn.getChildText("APPNO");
			
			int rw = bocB01Dao.updateInfo(id, appno);
			if(rw <= 0){
				throw new Exception("更新中行BOCB01接口结果失败");
			}
			
			//调用FTP附件中转(身份证复印件 ，征信业务授权书等)
			List<String> fileTypes = null;
			if(StringUtils.isBlank(bOCB01Bean.getSponsorType())){
				if(StringUtils.isBlank(bOCB01Bean.getSpouseId())){//主贷款人
					fileTypes =  Arrays.asList(FileTypeConstants.DALIST_TYPE_IDC, FileTypeConstants.DALIST_TYPE_IDRC, FileTypeConstants.DALIST_TYPE_CRD);
				}else{//配偶
					fileTypes =  Arrays.asList(FileTypeConstants.DALIST_TYPE_MATE_IDC, FileTypeConstants.DALIST_TYPE_MATE_IDRC, FileTypeConstants.DALIST_TYPE_MATE_CRD);
				}
			}else{//担保人
				fileTypes =  Arrays.asList(FileTypeConstants.DALIST_TYPE_SPONSOR_IDC, FileTypeConstants.DALIST_TYPE_SPONSOR_IDRC, FileTypeConstants.DALIST_TYPE_SPONSOR_CRD);
			}
			List<DataListEntity> fileList = datalistDao.getFileDataList(loanapplyNo, fileTypes);
			bocNetService.sendFtpAttachment(appno, fileList);
			logService.writeB01Log(logEntity, appno, loanapplyNo, billCode, LogEntity.RESULT_TYPE_SUCCESS, null);
			logger.info("征信调查调用成功,loanapplyNo:[{}], id：[{}],appno:[{}]", loanapplyNo, id, appno);
		} catch (Exception e) {
			logService.writeB01Log(logEntity, appno, loanapplyNo, billCode, LogEntity.RESULT_TYPE_ERROR, e.getMessage());
			logger.error("征信调查出现异常，loanapplyNo:[{}], id：[{}]，errMsg：[{}]", loanapplyNo, id, e);
			e.printStackTrace();
		} 
		return result;
	}
}
